package com.itsenpupulai.longlivetest;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.Log;


public class MD5Util {



	public static String getMD5Code(String info) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(info.getBytes("UTF-8"));
			byte[] encryption = md5.digest();

			StringBuffer strBuf = new StringBuffer();
			for (int i = 0; i < encryption.length; i++) {
				if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
					strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
				} else {
					strBuf.append(Integer.toHexString(0xff & encryption[i]));
				}
			}
			Log.e("MD5加密后字符： ---->", strBuf.toString());
			return strBuf.toString();
		} catch (Exception e) {
			return "";
		}
	}

	public static HashMap<String, Object> getDigestedMap() {

		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			String token = "simpleplan";
			String nonce = (int) (Math.random() * 100) + "";
			String timestamp = new Date().getTime() / 1000 + "";
			String uid = "411414";

			String temp = token + nonce + timestamp + uid;
			String signature = getMD5Code(temp);

			map.put("timestamp", timestamp);
			map.put("nonce", nonce);
			map.put("uid", uid);
			map.put("signature", signature);
			
			return map;
		} catch (Exception e) {
			e.printStackTrace();
//			MyToast.showToast(context, "数据加密异常", 0);
			return map;
		}
	}
	
	public static String getMD5Post(Map<String, Object> map) {

		
		try {
//			String appKey = "1";
//			String timestamp = TimeUtils.dateFormat.format(new Date().getTime());
//			String timestamp = new Date().getTime() + "";
//			String format = "json";
//			String version = "2.0.1";
//
//
////			map.put("appkey", appKey);
//			map.put("timestamp", timestamp);
//			map.put("format", format);
//			map.put("version", version);
//			map.put("apiversion", "V1");
			
			
			return getMD5Code(getSortMap(map));
		} catch (Exception e) {
			e.printStackTrace();
			return getMD5Code(getSortMap(map));
		}
	}
	
	//对map内数据以key值排序
	public static String getSortMap( Map<String, Object> map){
        String str = "33445d8b31fa81b444f3b8263c47dbfc";
        Collection<String> keyset= map.keySet();
        List<String> list = new ArrayList<String>(keyset);
        //对key键值按字典升序排序
        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
//            System.out.println("key键---值: "+list.get(i)+","+map.get(list.get(i)));
            str += list.get(i) + map.get(list.get(i));
        }
        str += "33445d8b31fa81b444f3b8263c47dbfc";

		Log.e("请求参数排序：-----》 ", str);
        return str ;
    }
	

}